from facility.contro_fn import MouseButton,KeyboardKey,InputController
from .setting import *
from facility.window_fn import Window
import time
from facility import Pic
from facility.pic_fn import rgb_to_hsv
import numpy as np
import cv2
from facility.ctx.redis_con import redis_connect
import re
from facility.time_fn import timer
from facility.pic_fn import rgb_to_binary
from .find import find_contours,display_counters

def op_distance(x1,x2):
    return max(x1[0]-x2[0],x1[1]-x2[1])


class Base(InputController):

    def __init__(self,window:Window):
        self.window = window


    def coordinate(self,map_name='无间之地'):
        reg = re.compile('(%s [1-9]\d{0,2}:[1-9]\d{0,2})'%map_name)
        encoding = 'gbk'

        for addr in self.process.search_by_regex(reg=reg, encoding=encoding):
            ads = addr[0]
            return str(ads.dump(),encoding=encoding, errors='ignore')



    def find_blood_bar(self):
        data = self.window.snap()
        data[CENTER_POINT[1]-48:CENTER_POINT[1]-44,CENTER_POINT[0]-18:CENTER_POINT[0]+18,:]=[255,255,255]
        data[545:,:,:]=[255,255,255]
        data[:,:70,:]=[255,255,255]
        data[484:555, 70:200, :] = [255, 255, 255]


        thresh = 35
        data = data - BLOOD_RGB
        data = np.sqrt(np.sum(np.square(data),axis=2))
        data[np.where(data<=thresh)]= True
        data[np.where(data>thresh)] = False
        data = np.array(data,dtype=np.uint8)

        contours = cv2.findContours(data,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        cn = np.array([np.average(i,axis=0).flatten() for i in contours[1] if i.shape[0]>20])

        return cn



    def find_circle_tile(self,circle=1,frame = None):
        if frame is not None:
            data=frame
        else:
            data = self.window.snap()
        x=48
        x_padding = x // 2

        y=32
        y_padding = y // 2

        points = []
        for i in range(circle):
            y = y*(i+1)
            x = x*(i+1)

            points.extend([
                (CENTER_POINT[0], CENTER_POINT[1] - y),
                (CENTER_POINT[0] + x, CENTER_POINT[1] - y),
                (CENTER_POINT[0] + x, CENTER_POINT[1]),
                (CENTER_POINT[0] + x, CENTER_POINT[1] + y),
                (CENTER_POINT[0], CENTER_POINT[1] + y),
                (CENTER_POINT[0] - x, CENTER_POINT[1] + y),
                (CENTER_POINT[0] - x, CENTER_POINT[1]),
                (CENTER_POINT[0] - x, CENTER_POINT[1] - y),
            ]
            )



        return [data[i[1]-y_padding:i[1]+y_padding,i[0]-x_padding:i[0]+x_padding,:] for i in points],points


    def find_monster(self,circle=1):

        data, points = self.find_circle_tile(circle)
        idx = 7

        data[idx] = data[idx][10:20,:,:]

        (Pic.load(data[idx]).display())
        #
        # imgs = [rgb_to_hsv(img) for img in data]
        # res = []
        #
        #
        # for idx,img in enumerate(imgs):
        #     white = 0
        #     for i in range(img.shape[0]):
        #         for j in range(img.shape[1]):
        #             if img[i, j, 0] < 90 and img[i, j, 1] < 90 and img[i, j, 2] > 200:
        #                 white += 1
        #     if white >8:
        #         res.append(idx)
        #
        # return [points[i]  for i in res]



    def find_treasure(self,circle=1):
        data, points = self.find_circle_tile(circle)
        res = []

        for i in range(data.__len__()):
            data[i] = data[i][15:25,:,:]


        for idx,img in enumerate(data):
            black = 0
            white = 0
            h,w,c=img.shape
            for i in range(h):
                for j in range(w):
                    r,g,b = img[i,j]
                    if 210 <=r<=235 and 215<=g<=238 and 205<=b<=225:
                        white +=1

                    if 100<=r<=110 and 90<=g<=105 and 80<=b<=95:
                        black +=1

            print(white,black)
            if 0<white<8 and 0<black<18:
                res.append(idx)


        return [points[i]  for i in res]



